﻿/*-------------------------------------------------------------------------
* 命名空间: XrayDirection.ValueConverters/MatToBitmapConverter
* 类       名: MatToBitmapConverter
* 功      能:  TD
* 时      间:  2024/1/27 14:48:41
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using OpenCvSharp;
using System;
using System.Globalization;
using System.Windows.Interop;
using System.Windows.Media.Imaging;

namespace XrayDirection.ValueConverters
{
    public class MatToBitmapConverter : OneWayConverter
    {
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && value is Mat mat)
            {
                BitmapSource bitmap = MatToBitmapSource(mat);
                return bitmap;
            }
            return null;
        }

        public static BitmapSource MatToBitmapSource(Mat mat)
        {
            var bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
            var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                bitmap.GetHbitmap(),
                IntPtr.Zero,
                System.Windows.Int32Rect.Empty,
                BitmapSizeOptions.FromWidthAndHeight(bitmap.Width, bitmap.Height));

            // 如果不这样做，会内存泄漏
            DeleteObject(bitmap.GetHbitmap());

            return bitmapSource;
        }

        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
    }
}
